package com.dddframework.web.core;

import com.dddframework.core.context.BaseContext;
import com.dddframework.core.context.SpringContext;
import com.dddframework.core.context.ThreadContext;
import com.dddframework.core.contract.constant.ContextConstants;
import com.dddframework.core.contract.exception.ServiceException;
import com.dddframework.web.config.BaseWebProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.dddframework.core.contract.constant.ContextConstants.ACCESS_TOKEN;


@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class AccessToken implements Serializable {
    private String accessToken;
    private LocalDateTime expireTime;
    private String tenantId;

    public static void expire() {
        BaseWebProperties baseWebProperties = SpringContext.getBean(BaseWebProperties.class);
        RedisTemplate redisTemplate = BaseContext.get(ContextConstants.REDIS_TEMPLATE);
        String accessTokenKey = baseWebProperties.getAuth().getTokenKeyCachePrefix() + ThreadContext.<AccessToken>get(ACCESS_TOKEN).getAccessToken();
        redisTemplate.expire(accessTokenKey, baseWebProperties.getAuth().getTokenExpire(), TimeUnit.HOURS);
    }

    public static AccessToken cache(String appId, String appSecret, Integer refresh) {
        // 校验AppID与AppSecret
        BaseWebProperties openApiConfig = SpringContext.getBean(BaseWebProperties.class);
        BaseWebProperties.Auth.App app = openApiConfig.getAuth().getApp(appId, appSecret);
        if (app == null) {
            throw new ServiceException("appId或appSecret不正确！");
        }
        String token = UUID.randomUUID().toString();
        String accessTokenKey = openApiConfig.getAuth().getTokenKeyCachePrefix() + token;
        AccessToken accessToken = AccessToken.builder().accessToken(token).expireTime(LocalDateTime.now().plusHours(openApiConfig.getAuth().getTokenExpire())).tenantId(app.getTenantId()).build();
        RedisTemplate redisTemplate = BaseContext.get(ContextConstants.REDIS_TEMPLATE);
        redisTemplate.opsForValue().set(accessTokenKey, accessToken, openApiConfig.getAuth().getTokenExpire(), TimeUnit.HOURS);
        return accessToken;
    }
}
